package com.example.design.pattern.structure

import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy

fun main() {
    val internet =
        Proxy.newProxyInstance(
            RouteProxy::class.java.classLoader,
            RouteProxy::class.java.interfaces,
            BlackListFilter(RouteProxy())
        ) as Internet?
    internet?.httpAccess("A")
    internet?.httpAccess("B")
    internet?.httpAccess("D")
}

interface Internet {
    fun httpAccess(url: String)
}


class Modem(password: String) : Internet {
    override fun httpAccess(url: String) {
        println("正在拨号:$url")
    }

}

class RouteProxy : Internet {
    private val modem = Modem("11111")

    override fun httpAccess(url: String) {
        modem.httpAccess(url)
    }

}

class BlackListFilter(private val any: Any) : InvocationHandler {
    private val list = listOf("A", "B", "C")

    override fun invoke(p0: Any?, p1: Method?, p2: Array<out Any>?): Any? {
        p2?.let {
            println(p0)
            println(p1)
            val url = it[0]
            println(url is String)
            return if (list.any { a -> a == url }) {
                println("黑名单")
                null
            } else {
                println(any)
                p1?.invoke(any, url)
            }
        }
        return null
    }

}